//1. 头文件简洁
// logger.h 不需要包含复杂的spdlog头文件
// 减少了编译依赖
//2. 编译隔离
// 修改spdlog相关代码不会导致大量重新编译
// 只需重新编译logger.cpp
//3. 实现灵活性
// 可以随时更换日志库实现
// 只需修改mylogger类，不影响外部接口

#include "logger.h"

#include "spdlog/async.h"
#include "spdlog/cfg/env.h"
#include "spdlog/sinks/basic_file_sink.h"
#include "spdlog/sinks/rotating_file_sink.h"
#include "spdlog/spdlog.h"
class mylogger
{
   public:
    std::shared_ptr<spdlog::logger> instance;
};

SPDLogger::SPDLogger()
{
    my_logger_ = std::make_shared<mylogger>();
}

SPDLogger::~SPDLogger() {}

SPDLogger &SPDLogger::instance()
{
    static SPDLogger l;
    return l;
}

void SPDLogger::init(const std::string &name, const std::string &filepath, int level)
{
    try
    {
        spdlog::set_level(static_cast<spdlog::level::level_enum>(level));
        my_logger_->instance = spdlog::rotating_logger_mt(name, filepath, 1024 * 1024 * 64, 6);
        my_logger_->instance->set_pattern("%Y-%m-%d %H:%M:%S.%e	%l [%n-%P] [%t] %v");
        my_logger_->instance->flush_on(spdlog::level::info);
        spdlog::flush_every(std::chrono::seconds(2));
    }
    catch (const std::exception &e)
    {
        std::cout << "init log exception: " << e.what() << std::endl;
    }
}

void SPDLogger::uninit()
{
    spdlog::shutdown();
}

void SPDLogger::setLoggerLevel(int level)
{
    spdlog::set_level(static_cast<spdlog::level::level_enum>(level));
}

void SPDLogger::write(int level, const std::string &logText)
{
    try
    {
        if (my_logger_)
        {
            my_logger_->instance->log(static_cast<spdlog::level::level_enum>(level), logText);
        }
        else
        {
            std::cout << logText << std::endl;
        }
    }
    catch (...)
    {
    }
}